import { _decorator, CircleCollider2D, Collider2D, Color, Component, Contact2DType, Enum, Label, math, Node, Sprite, SpriteFrame, Tween, tween, UIOpacity, UITransform, Vec3 } from 'cc';
import { Unit } from './Unit';
import { Global, LootData, LootType, UnitType } from '../Util/Global';
import AssetsMgr from '../Model/AssetsMgr';
import { FactoryCom } from './Component/FactoryCom';
import GameEventMgr, { GameEvent } from '../Model/GameEventMgr';
import { EconomicCom } from './Component/EconomicCom';
import { LevelUpCom } from './Component/LevelUpCom';
import { Tools } from '../Util/Tools';
const { ccclass, property } = _decorator;

@ccclass('Loot')
export class Loot extends Unit {

    @property(Sprite)
    sprite: Sprite = null;
    @property(Label)
    label: Label = null;
    @property({
        type: Enum(LootType),  // 将 Direction 枚举类型传递给 Enum
        displayName: "掉落物类型", // 在编辑器中显示提示信息
    })
    loot_id: LootType = LootType.Mine;

    @property
    content: number = 0;//携带数量

    protected trigger: CircleCollider2D = null;
    protected tweenArr: Tween<Node>[] = [];

    target: FactoryCom = null;
    start(): void {
        super.start();

        this.unitType = UnitType.Loot;

        for (let co of this.colliders) {
            if (co.tag == 1) {
                this.trigger = co as CircleCollider2D;
                this.trigger.radius = this.alertFieldRadius;

                //监听传感器碰撞事件 二者的rigibody和collider二者任意一个的group符合碰撞就会触发碰撞事件
                this.trigger.on(Contact2DType.BEGIN_CONTACT, this.onTriggerEnter, this);
                break;
            }
        }

        this.label.node.active = false;

    }

    /**重新激活的第一帧调用，代替onEnable */
    protected lateStart(): void {
        super.lateStart();

        AssetsMgr.getRes(LootData.LootMap.get(this.loot_id).iconPath, SpriteFrame, (sp) => {
            this.sprite.spriteFrame = sp;
        });
        if (this.loot_id == LootType.Relic) {
            // this.sprite.color = Tools.hex2color('#1DE22C');
            // AssetsMgr.getRes('texture/btn/icon_exclamationLarge/spriteFrame', SpriteFrame, (sp) => {
            //     let tip = this.node.getChildByName('relic_tip');
            //     if (tip == null) {
            //         tip = new Node();
            //         tip.parent = this.node;
            //         tip.scale.set(0.8, 0.8);
            //     }
            //     tip.active = true;
            //     let spr = tip.getComponent(Sprite) || tip.addComponent(Sprite);
            //     spr.spriteFrame = sp;
            //     spr.color = Tools.hex2color('#E27E11');
            // });
        }
        else if (this.loot_id == LootType.Shield) {
            this.sprite.color = Tools.hex2color('#00BEF9');

        }

        //延迟播放，先让this.unitWorldPos被赋值
        let tw = tween(this.node).call(() => {
            if (this.content <= 0) {//作为icon显示
                this.TweenDiffusionHide();
                this.deathTime = 3;
            }
            else {
                this.TweenDiffusionHide(false);
                if (this.loot_id == LootType.Relic) {
                    this.label.string = '';
                }
                else {
                    this.label.string = this.content.toString();
                }
                this.label.node.active = true;

                this.deathTime = 30;
            }
        });

        this.TweenNextPlay(tw);
    }
    protected onEnable(): void {
        super.onEnable();

        // let tip = this.node.getChildByName('relic_tip');
        // if (tip) {
        //     tip.active = false;
        // }
    }

    protected onDisable(): void {
        super.onDisable();

        let opacity = this.getComponent(UIOpacity) || this.node.addComponent(UIOpacity);
        opacity.opacity = 255;
        this.label.string = '';
        this.content = 0;
        this.sprite.color = Color.WHITE;
    }

    protected onTriggerEnter(selfCollider: Collider2D, otherCollider: Collider2D) {
        super.onTriggerEnter(selfCollider, otherCollider);
        // 只在两个碰撞体开始接触时被调用一次

        let target = otherCollider.node.getComponent(FactoryCom);
        if (target && target.unit != null && !target.unit.death) {
            if (this.content > 0) {
                this.target = target;
                this.TweenMoveToTarget(this.target.node);
            }
        }

    }

    DestroySelf(reason?: string | number) {
        super.DestroySelf(reason);
        this.tweenArr = [];
        Tween.stopAllByTarget(this.node);
    }

    private _wpos = new Vec3;
    /**移动到目标位置 */
    TweenMoveToTarget(node: Node) {

        let tw = tween(this.node).call(() => {
            let targetTran = node.getComponent(UITransform);
            this.node.getWorldPosition(this._wpos);
            let pos = targetTran.convertToNodeSpaceAR(this._wpos);
            this.node.setPosition(pos);
            this.node.parent = node;
        })
            .to(1, { position: Vec3.ZERO.clone() }, { easing: 'quintOut' }).call(() => {
                this.DestroySelf();

                if (this.target
                    && !Global.gameManager.gameover
                    && (this.target.unit == Global.gameManager.playerUnit)) {//暂设掉落物只对玩家有用

                    switch (this.loot_id) {
                        case LootType.Technology:
                            Global.gameManager.playerData.technologyPoint += this.content;
                            break;
                        case LootType.Mine:
                            let ecom = Global.gameManager.playerUnit.getComponent(EconomicCom);
                            if (ecom) {
                                ecom.AddMineRes(this.content);
                                GameEventMgr.Dispatch(GameEvent.ECViewDataChangeToTip, 'mine', this.content);
                            }
                            break;
                        case LootType.Relic:
                            this.target.unit.getComponent(LevelUpCom)?.AddRelic(this.content);
                            break;
                    }
                    GameEventMgr.Dispatch(GameEvent.PlayerDataChange);
                }
            });

        this.TweenNextPlay(tw);
    }

    /**掉落消隐 */
    TweenDiffusionHide(hide = true) {

        let randomAngle = 360 * math.random();
        let radius = 30;
        // 将随机角度转换为弧度
        let radian = randomAngle * (Math.PI / 180);
        // 计算在扇形区域内的随机点
        let posX = radius * Math.cos(radian);
        let posY = radius * Math.sin(radian);

        let hidePos = new Vec3(posX, posY, 0);
        this.node.getWorldPosition(this._wpos);
        hidePos = this._wpos.add(hidePos);
        Global.GameNodeTran.convertToNodeSpaceAR(hidePos, hidePos);

        let opacity: UIOpacity = null;
        let tw = tween(this.node)
            .to(0.5, { position: hidePos }, { easing: 'quintOut' })
            .to(0.5, {}, {
                onStart: (target) => {
                    opacity = this.getComponent(UIOpacity) || this.node.addComponent(UIOpacity);
                },
                onUpdate: (target, ratio) => {
                    if (opacity && hide) {
                        opacity.opacity = (1 - ratio) * 255;
                    }
                },
                easing: 'quintOut'
            })
            .call(() => {
                if (hide) {
                    this.DestroySelf();
                }
            });

        this.TweenNextPlay(tw);
    }

    currentTw: Tween<Node> = null;
    /**通过队列依次播放该对象所以的动画 */
    TweenNextPlay(tw?: Tween<Node>) {

        if (this.currentTw) {
            if (tw) {
                this.tweenArr.push(tw);
            }
        }
        else {
            this.currentTw = tw || this.tweenArr.shift();

            if (this.currentTw) {
                this.currentTw.call(() => {
                    this.currentTw = null;
                    this.TweenNextPlay();
                }).start();
            }
        }
    }
}


